package com.mrx.xfriendship.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mrx.xfriendship.model.dto.SystemInfoDTO;
import com.mrx.xfriendship.service.IPostService;
import com.mrx.xfriendship.service.IRedisService;
import com.mrx.xfriendship.service.ISystemInfoService;
import com.mrx.xfriendship.service.IUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Optional;

import static com.mrx.xfriendship.service.ISystemInfoService.SITE_PV_KEY;

/**
 * @author Mr.X
 * @since 2023-01-21 15:30
 */
@Service
public class SyncService {

    private static final Logger logger = LoggerFactory.getLogger(SyncService.class);

    @DubboReference
    private IRedisService redisService;

    @DubboReference
    private IPostService postService;

    @DubboReference
    private ISystemInfoService systemInfoService;

    @DubboReference
    private IUserService userService;

    private static final String SYNC_CRON = "0 0/1 * * * ?";

    @Scheduled(cron = SYNC_CRON)
    public void syncSitePV() {
        JSONObject pvList = redisService.getSitePvList(true);
        logger.debug("开始同步 pv 数据: {}", pvList);
        Optional.ofNullable(pvList)
                .map(it -> {
                    SystemInfoDTO dto = new SystemInfoDTO();
                    dto.setKey(SITE_PV_KEY);
                    dto.setValue(it.toJSONString());
                    return dto;
                })
                .ifPresent(systemInfo -> systemInfoService.setSystemInfo(systemInfo));
    }

    @Scheduled(cron = SYNC_CRON)
    public void syncPostPV() {
        JSONObject pvList = redisService.getPostPVList(true);
        logger.debug("开始同步 PostPv 数据: {}", pvList);
        Optional.ofNullable(pvList).ifPresent(it -> postService.syncPV(it));
    }

    @Scheduled(cron = SYNC_CRON)
    public void syncMaxOnLineUserNumber() {
        Integer onlineUser = redisService.getOnlineUser();
        logger.debug("开始同步 在线用户 数据: {}", onlineUser);
        userService.syncMaxOnLineUserNumber(onlineUser);
    }

}
